<%--
  Created by IntelliJ IDEA.
  User: liyunze
  Date: 2021/1/12
  Time: 下午7:32
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <c:import url="/template/_header.jsp"/>
    <title>用户管理-知了[团队知识管理应用]</title>
</head>
<body>
<div class="re-main">
    <c:import url="/template/_navbar.jsp"/>
    <div class="re-box-6 re-grey mt-85">
        <div class="container">
            <div class="row vertical-gap md-gap">
                <div class="col-lg-12">
                    <div class="re-box re-box-decorated">
                        <div class="resource-post">
                            <div class="resource-post-box pt-30 pb-25">
                                <div class ="container">
                                    <div class="re-form-group"  style="line-height:38px; margin-top: -5px; margin-bottom: 15px">
                                        <a href="../manage">管理</a>&nbsp;|&nbsp;用户管理
                                    </div>
                                    <div class="resource-comment-text">
                                        <h1 class="h4 mnt-5 mb-9"><span id="userName">用户管理</span></h1>
                                    </div>
                                    <div class="container" id="loading-container" style="margin-top:5px;display: block">
                                        <div class="front-loading">
                                            <img src="../assets/images/loading.gif"/>
                                        </div>
                                        <div class="panel-body text-center">正在加载请稍候</div>
                                    </div>
                                    <div id="userList"></div>
                                    <div id="userManagerList"></div>
                                    <div id="userApplyList"></div>
                                    <div id="userRefuseList"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <c:import url="../template/_footer.jsp"/>
</div>
<%--新增用户的modal--%>
<div class="modal fade" id="addUser" tabindex="-1" role="dialog" aria-labelledby="addMemberLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="addUserLabel">新增用户</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <div class="col-lg-7">
                        <label>姓名</label>
                        <input type="text" class="form-control front-no-box-shadow" name="applicationDes" id="realName" placeholder="必填"/>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-lg-7">
                        <label>手机</label>
                        <input type="text" class="form-control front-no-box-shadow" name="applicationDes" id="account" placeholder="必填"/>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-lg-7">
                        <label>邮箱</label>
                        <input type="text" class="form-control front-no-box-shadow" name="applicationDes" id="mail" placeholder="必填"/>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-lg-7">
                        <label>角色</label>
                        <select class="selectpicker form-control" id="chooseRole" name="chooseRole" data-live-search="true"></select>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" id="btn_add" class="btn btn-primary" data-dismiss="modal"
                        onclick="addUser()">新增</button>
            </div>
        </div>
    </div>
</div>
<%--修改用户的modal--%>
<div class="modal fade" id="modifyUser" tabindex="-1" role="dialog" aria-labelledby="addMemberLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="modifyUserLabel">编辑用户</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <div class="col-lg-7">
                        <label>姓名</label>
                        <input type="text" class="form-control front-no-box-shadow" name="applicationDes" id="modifyRealName" placeholder="必填"/>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-lg-7">
                        <label>手机</label>
                        <input type="text" class="form-control front-no-box-shadow" name="applicationDes" id="modifyAccount" placeholder="必填"/>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-lg-7">
                        <label>邮箱</label>
                        <input type="text" class="form-control front-no-box-shadow" name="applicationDes" id="modifyMail" placeholder="必填"/>
                    </div>
                </div>
                <div class="form-group" id="role">
                    <div class="col-lg-7">
                        <label>角色</label>
                        <select class="selectpicker form-control" id="ModifyChooseRole" name="chooseRole" data-live-search="true"></select>
                    </div>
                </div>
                <div class="form-group" style="display: none">
                    <div class="col-lg-7">
                        <label>ID</label>
                        <input type="text" class="form-control front-no-box-shadow" name="applicationDes" id="modifyId" placeholder="必填"/>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" id="modify_btn_add" class="btn btn-primary" data-dismiss="modal"
                        onclick="modifyUser()"><a>确定</a></button>
            </div>
        </div>
    </div>
</div>
<%--提示用户密码的modal--%>
<div class="modal fade" id="defaultPswd-modal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">用户密码</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            </div>
            <div class="modal-body">
                <div class="col-lg-7">
                    <div style="float: left" id="defaultPswd-title"></div>
                    <div style="float: left" id="defaultPswd-text"></div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-dismiss="modal"><a>确定</a></button>
            </div>
        </div>
    </div>
</div>
</body>
<!-- START: Scripts -->
<c:import url="../template/_include_js.jsp"/>
<script>
    let searchValue = "";
    let state = 1;
    let changeable = 0;
    showUsers(1,'');

    // 不同情况下回车键触发的函数
    document.addEventListener("keyup",function(e){
        if(e.keyCode == 13){

            if(state == 1){
                search();
            }
            if(state == 2){
                searchManager();
            }
            if(state == 3){
                searchApply();
            }
            if(state == 4){
                searchRefuse();
            }
        }
    });

    // 模糊搜索函数，分别搜索用户，管理员，申请者，已拒绝
    function search(){
        const inputValue = $('#searchBox').val();
        searchValue = inputValue;
        showUsers(1,inputValue);
    }
    function searchManager(){
        const inputValue = $('#searchBoxManager').val();
        searchValue = inputValue;
        showManager(1,inputValue);
    }
    function searchApply(){
        const inputValue = $('#searchBoxApply').val();
        searchValue = inputValue;
        showApply(1,inputValue);
    }
    function searchRefuse(){
        const inputValue = $('#searchBoxRefuse').val();
        searchValue = inputValue;
        showRefuse(1,inputValue);
    }

    // 展示固定页面的用户
    function getAppPage(page){
        showUsers(page, searchValue);
    }

    // 展示用户列表，分别是用户，管理员，申请者，已拒绝
    function showUsers(page, search) {
        state = 1;
        $.ajax({
            url: "/user/userManagement",
            type: "get",
            data: {page:page, search:search},
            beforeSend:function(){
                $("#loading-container").css("display","block");
                $("#userList").hide();
                $("#userManagerList").hide();
                $("#userApplyList").hide();
                $("#userRefuseList").hide();
            },
            success: function (data) {
                $("#userManagerList").hide();
                $("#userApplyList").hide();
                $("#userRefuseList").hide();
                $('#userList').html(data);
                $("#loading-container").css("display","none");
                $("#userList").show();
            },
            error: function () {
                $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '显示用户失败！'});
            }
        });
    }
    function showManager(page, search){
        state = 2;
        $.ajax({
            url: "/user/userManagerManagement",
            type: "get",
            data: {page:page, search:search},
            beforeSend:function(){
                $("#loading-container").css("display","block");
                $("#userList").hide();
                $("#userManagerList").hide();
                $("#userApplyList").hide();
                $("#userRefuseList").hide();
            },
            success: function (data) {
                $("#userList").hide();
                $("#userApplyList").hide();
                $("#userRefuseList").hide();
                $('#userManagerList').html(data);
                $("#loading-container").css("display","none");
                $("#userManagerList").show();
            },
            error: function () {
                $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '显示管理员失败！'});
            }
        });
    }
    function showApply(page, search){
        state = 3;
        $.ajax({
            url: "/user/userApplyManagement",
            type: "get",
            data: {page:page, search:search},
            beforeSend:function(){
                $("#loading-container").css("display","block");
                $("#userList").hide();
                $("#userManagerList").hide();
                $("#userApplyList").hide();
                $("#userRefuseList").hide();
            },
            success: function (data) {
                $("#userList").hide();
                $("#userManagerList").hide();
                $("#userRefuseList").hide();
                $('#userApplyList').html(data);
                $("#loading-container").css("display","none");
                $("#userApplyList").show();
            },
            error: function () {
                $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '显示申请者失败！'});
            }
        });
    }
    function showRefuse(page, search){
        state = 4
        $.ajax({
            url: "/user/userRefuseManagement",
            type: "get",
            data: {page:page, search:search},
            beforeSend:function(){
                $("#loading-container").css("display","block");
                $("#userList").hide();
                $("#userManagerList").hide();
                $("#userApplyList").hide();
                $("#userRefuseList").hide();
            },
            success: function (data) {
                $("#userList").hide();
                $("#userManagerList").hide();
                $("#userApplyList").hide();
                $('#userRefuseList').html(data);
                $("#loading-container").css("display","none");
                $("#userRefuseList").show();
            },
            error: function () {
                $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: '显示已拒绝失败'});
            }
        });
    }

    // 新增用户
    function showUserAdd(){
        $('#addUser').modal();
        $('#account').val("");
        $('#realName').val("");
        $('#mail').val("");
        $('#chooseRole').val("");
    }
    function addUser() {
        const number = $("#account").val();
        const name = $("#realName").val();
        const mail = $("#mail").val();
        const role = $("#chooseRole").val();
        let trueMessage = 1;
        let roleId = 0;

        $('#account').val("");
        $('#realName').val("");
        $('#mail').val("");
        $('#chooseRole').val("");

        if(role == "用户管理员"){
            roleId = 2;
        }else if(role == "内容管理员"){
            roleId = 3;
        }else if(role == "系统管理员"){
            roleId = 4;
        }

        const newUser = {
            account: number,
            realName: name,
            mail: mail,
            roleId: roleId
        };

        if(number == ""||name == ""||mail == ""||role == ""){
            $.fillTipBox({type: 'danger', icon: 'glyphicon-ok-sign', content: '添加失败，信息填写不完整'});
            trueMessage = 0;
        }else if(!(isMobile(number))){
            $.fillTipBox({type: 'danger', icon: 'glyphicon-ok-sign', content: '添加失败，手机号码有误'});
            trueMessage = 0;
        }else if(!(isMail(mail)==1)){
            $.fillTipBox({type: 'danger', icon: 'glyphicon-ok-sign', content: '添加失败，邮箱格式有误'});
            trueMessage = 0;
        }
        if(trueMessage == 1){
            $.ajax({
                type: "post",
                url: "/user/add",
                data: newUser,
                success: function (jsonObject) {
                    if (jsonObject.code === 200) {
                        $.fillTipBox({type: 'success', icon: 'glyphicon-ok-sign', content: '添加用户成功'});
                        $("#defaultPswd-title").html("该用户默认密码为：");
                        $("#defaultPswd-text").html(jsonObject['defaultPassword']);
                        $("#defaultPswd-modal").modal();
                        showUsers(1,'');
                    } else{
                        $.fillTipBox({type: 'danger', icon: 'glyphicon-ok-sign', content: '添加失败，手机/邮箱重复'});
                    }
                },
            });
        }
    }

    // 删除用户
    function confirmDeleteUser(id) {
        $.tipModal('confirm', 'danger', '确认删除此用户吗？', function (result) {
            if (result == true) {
                userDelete(id);
            }
        });
    }
    function userDelete(userId) {
        const id = userId;
        $.ajax({
            type: "delete",
            url: "/user/" + id,
            contentType: "application/json",
            success: function (jsonObject) {
                if (jsonObject.code === 200) {
                    $.fillTipBox({type: 'success', icon: 'glyphicon-ok-sign', content: '删除用户成功'});
                    showUsers(1,'');
                } else
                    console.log("失败")
            },
        });
    }

    // 编辑用户
    function showUserModify(name, account, mail, roleId, id, permission){
        if(permission == 1 && roleId != 1){
            document.getElementById("role").style.display="";
        }else {
            document.getElementById("role").style.display="none";
        }
        let role;
        $('#modifyUser').modal();
        $('#modifyRealName').val(name);
        $('#modifyAccount').val(account);
        $('#modifyMail').val(mail);
        $('#modifyId').val(id);
        if(roleId == 0){
            role = "普通用户";
            changeable = 0;
        }else if(roleId == 1){
            role = "超级管理员";
            changeable = 1;
        }else if(roleId == 2){
            role = "用户管理员";
            changeable = 0;
        }else if(roleId == 3){
            role = "内容管理员";
            changeable = 0;
        }else if(roleId == 4){
            role = "系统管理员";
            changeable = 0;
        }

        $('#ModifyChooseRole').val(role);
        $('#ModifyChooseRole').selectpicker('refresh');


    }
    function modifyUser() {
        const role = $("#ModifyChooseRole").val();
        const name = $("#modifyRealName").val();
        const number = $("#modifyAccount").val();
        const mail = $("#modifyMail").val();
        const id = $("#modifyId").val();
        var trueMessage = 1;
        var roleId = 0;

        $('#modifyAccount').val("");
        $('#modifyRealName').val("");
        $('#modifyMail').val("");
        $('#ModifyChooseRole').val("");
        $('#modifyId').val("");

        if(changeable == 1)
        {
            roleId = 1;
        }else {
            if(role == "超级管理员"){
                roleId = 1;
            }else if(role == "用户管理员"){
                roleId = 2;
            }else if(role == "内容管理员"){
                roleId = 3;
            }else if(role == "系统管理员"){
                roleId = 4;
            }
        }
        const modifyUser = {
            account: number,
            realName: name,
            mail: mail,
            roleId: roleId
        };

        if(number == ""||name == ""||mail == ""||role == ""){
            $.fillTipBox({type: 'danger', icon: 'glyphicon-ok-sign', content: '修改失败，信息填写不完整'});
            trueMessage = 0;
        }else if(!(isMobile(number))){
            $.fillTipBox({type: 'danger', icon: 'glyphicon-ok-sign', content: '修改失败，手机号码有误'});
            trueMessage = 0;
        }else if(!(isMail(mail)==1)){
            $.fillTipBox({type: 'danger', icon: 'glyphicon-ok-sign', content: '修改失败，邮箱格式有误'});
            trueMessage = 0;
        }
        if(trueMessage == 1){
            $.ajax({
                type: "patch",
                url: "/user/modify/" + id,
                data: modifyUser,
                success: function (jsonObject) {
                    if (jsonObject.code === 200){
                        $.fillTipBox({type: 'success', icon: 'glyphicon-ok-sign', content: '编辑用户成功'});
                        showUsers(1,'');
                    }
                    else{
                        $.fillTipBox({type: 'danger', icon: 'glyphicon-ok-sign', content: '编辑失败，手机/邮箱重复'});
                    }
                },
            });
        }
    }

    // 权限
    function applyToUser(id){
        if(${sessionScope.roleId == 1 || sessionScope.roleId == 2}){
            const applyId = id;
            $.ajax({
                type: "patch",
                url: "/user/applyToUser/" + applyId,
                success: function (jsonObject) {
                    if (jsonObject.code === 200){
                        $.fillTipBox({type: 'success', icon: 'glyphicon-ok-sign', content: '编辑用户成功'});
                        $("#defaultPswd-title").html("该用户默认密码为：");
                        $("#defaultPswd-text").html(jsonObject.defaultPassword);
                        $("#defaultPswd-modal").modal();
                        showApply(1,'');
                    }
                    else{
                        console.log("失败")
                    }
                },
            });
        }else {
            showWrongTip();
        }
    }
    function applyToNo(id){
        if(${sessionScope.roleId == 1 || sessionScope.roleId == 2}){
            const applyId = id;
            $.ajax({
                type: "patch",
                url: "/user/applyToNo/" + applyId,
                success: function (jsonObject) {
                    if (jsonObject.code === 200){
                        $.fillTipBox({type: 'success', icon: 'glyphicon-ok-sign', content: '编辑用户成功'});
                        showApply(1,'');
                    }
                    else{
                        console.log("失败")
                    }
                },
            });
        }else {
            showWrongTip();
        }
    }
    function refuseToUser(id){
        if(${sessionScope.roleId == 1 || sessionScope.roleId == 2}){
            const applyId = id;
            $.ajax({
                type: "patch",
                url: "/user/applyToUser/" + applyId,
                success: function (jsonObject) {
                    if (jsonObject.code === 200){
                        $.fillTipBox({type: 'success', icon: 'glyphicon-ok-sign', content: '编辑用户成功'});
                        showRefuse(1,'');
                    }
                    else{
                        console.log("失败")
                    }
                },
            });
        }else {
            showWrongTip();
        }
    }
    function deleteApply(id){
        if(${sessionScope.roleId == 1 || sessionScope.roleId == 2}){
            const applyId = id;
            $.ajax({
                type: "patch",
                url: "/user/deleteApply/" + applyId,
                success: function (jsonObject) {
                    if (jsonObject.code === 200){
                        $.fillTipBox({type: 'success', icon: 'glyphicon-ok-sign', content: '编辑用户成功'});
                        showRefuse(1,'');
                    }
                    else{
                        console.log("失败")
                    }
                },
            });
        }else {
            showWrongTip();
        }
    }

    // 权限
    function showWrongTip(){
        $.fillTipBox({type: 'warning', icon: 'glyphicon-ok-sign', content: '无权限'});
    }

    // 激活appKey
    function confirmAppKey(id) {
        if ($("#" + id + "-appKey").html().indexOf("未激活") == -1) {
            $.tipModal('confirm', 'danger', '确认要为此用户更新appKey？', function (result) {
                if (result == true) {
                    resetAppKey(id, "更新");
                }
            });
        } else {
            $.tipModal('confirm', 'danger', '确认要为此用户分配appKey？', function (result) {
                if (result == true) {
                    resetAppKey(id, "激活");
                }
            });
        }
    }
    function resetAppKey(userId, tip) {
        $.ajax({
            type: "post",
            url: "/user/resetAppKey",
            data: {
                userId: userId
            },
            success: function (jsonObject) {
                if (jsonObject.code === 200){
                    $.fillTipBox({type: 'success', icon: 'glyphicon-ok-sign', content: tip + 'appKey成功'});
                    $("#" + userId + "-appKey").html("appKey：" + jsonObject.result.appKey);
                } else {
                    $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: tip + 'appKey失败！'});
                }
            },
            error: function () {
                $.fillTipBox({type: 'danger', icon: 'glyphicon-exclamation-sign', content: tip + 'appKey失败！'});
            }
        });
    }

    // 重置密码
    function confirmResetPassword(id) {
        $.tipModal('confirm', 'danger', '确认重置此用户的密码吗？', function (result) {
            if (result == true) {
                resetPassword(id);
            }
        });
    }
    function resetPassword(userId){
        const resetId = userId;
        $.ajax({
            type: "patch",
            url: "/user/resetPassword/" + resetId,
            success: function (jsonObject) {
                if (jsonObject.code === 200){
                    $.fillTipBox({type: 'success', icon: 'glyphicon-ok-sign', content: '重置密码成功'});
                    $("#defaultPswd-title").html("该用户密码被重置为：");
                    $("#defaultPswd-text").html(jsonObject.defaultPassword);
                    $("#defaultPswd-modal").modal();
                }
            },
        });
    }

    // 检查手机和邮箱格式
    function isMobile(phone){
        let isPhone = 1;
        var phone = phone;
        if(!(phone.length == 11)){
            isPhone = 0;
            return isPhone;
        }
        if(!(phone.substring(0,1) == 1)){
            isPhone = 0;
            return isPhone;
        }
        for(i = 0; i<phone.length; i++){
            num = phone.substring(i, i+1);
            if(!(num==0||num==1||num==2||num==3||num==4||num==5||num==6||num==7||num==8||num==9)){
                isPhone = 0;
                return isPhone;
            }
        }
        return isPhone;
    }
    function isMail(mail){
        let i;
        let isMail = 0;
        const mailLast = mail.substring(mail.length - 1, mail.length);
        const mailFirst = mail.substring(0,1);
        for(i = 0; i<mail.length; i++){
            const word = mail.substring(i, i + 1);
            if(!((word>='a'&& word<='z')||(word>='A'&& word<='Z')||(word>='0'&& word<='9')||(word == "@")||(word == "_")||(word == "-")||(word == "."))){
                return isMail;
            }
        }
        if(mailFirst == "@"||mailLast == "@"){
            return isMail;
        }
        for(i = 0; i<mail.length; i++){
            const num = mail.substring(i, i+1);
            if(num == "@"){
                isMail = isMail + 1 ;
            }
        }
        return isMail;
    }
    // 更新下拉菜单
    $(document).ready(function () {
        $.ajax({
            type: 'post',
            url:"/user/getRoles",
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    var add_Role = '<option value="' + data[i] + '">'+ data[i] + '</option>';
                    $('#chooseRole').append(add_Role);
                    $('#ModifyChooseRole').append(add_Role);
                }
                add_Role = '<option value="超级管理员" disabled>'+ "超级管理员" + '</option>';
                $('#ModifyChooseRole').append(add_Role);
                $('#chooseRole').selectpicker('refresh');
                $('#ModifyChooseRole').selectpicker('refresh');
            }
        })
    })
</script>
</html>